package com.ukefu.webim.util.impl;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.util.event.AiEvent;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.ChatMessageRepository;
import com.ukefu.webim.service.repository.ConsultInviteRepository;
import com.ukefu.webim.util.MessageUtils;
import com.ukefu.webim.util.OnlineUserUtils;
import com.ukefu.webim.util.disruptor.ai.AiMessageProcesserInterface;
import com.ukefu.webim.util.event.AiMessageAskProcesser;
import com.ukefu.webim.util.event.AiMessageOtherProcesser;
import com.ukefu.webim.util.event.AiMessageSmartProcesser;
import com.ukefu.webim.util.router.OutMessageRouter;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.model.AiConfig;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.CousultInvite;
import com.ukefu.webim.web.model.DisUser;
import com.ukefu.webim.web.model.MessageOutContent;

@Component
public class AiMessageProcesserImpl implements AiMessageProcesserInterface{
	
	
	@Autowired()
	private AiMessageAskProcesser aiMessageLevel1 ;
	
	@Autowired
	private AiMessageSmartProcesser aiMessageLevel2 ;
	
	@Autowired
	private AiMessageOtherProcesser otherAiMessageLevel ;
	
	@Autowired
	private ChatMessageRepository chatMessageRes ;
	
	@Autowired
	private AiMRoundsProcesserImpl aiMroundsProcesser ;
	
	@Autowired
	private AiMRoundsReplyImpl aiMroundsReply ;

	/**
	 * 
	 */
	@Override
	public MessageOutContent onEvent(AiEvent event, long arg1, boolean arg2) {
		ChatMessage data = chat((ChatMessage) event.getEvent()) ;
		MessageOutContent outMessage = null ;
		if(data != null ){
			final AiUser aiUser = (AiUser) CacheHelper.getAiUserCacheBean().getCacheObject(data.getUserid(),UKDataContext.SYSTEM_ORGI) ;
			outMessage = MessageUtils.createAiMessage(data , data.getAppid(), data.getChannel(), UKDataContext.CallTypeEnum.OUT.toString() , UKDataContext.AiItemType.AIREPLY.toString() , !StringUtils.isBlank(data.getMsgtype()) ? data.getMsgtype() : UKDataContext.MediaTypeEnum.TEXT.toString(), aiUser.getUserid()) ;
			
			if(!StringUtils.isBlank(data.getUserid()) && UKDataContext.MessageTypeEnum.MESSAGE.toString().equals(data.getType())){
	    		if(!StringUtils.isBlank(data.getTouser())){
		    		OutMessageRouter router = null ; 
		    		router  = (OutMessageRouter) UKDataContext.getContext().getBean(data.getChannel()) ;
		    		if(router!=null){
		    			router.handler(data.getTouser(), UKDataContext.MessageTypeEnum.MESSAGE.toString(), data.getAppid(), outMessage);
		    		}
		    	}
	    	}
		}
		return outMessage;
	}
	
	public ChatMessage chat(ChatMessage message){
		final AiUser aiUser = (AiUser) CacheHelper.getAiUserCacheBean().getCacheObject(message.getUserid(),UKDataContext.SYSTEM_ORGI) ;
		final AiConfig aiConfig = AiUtils.initAiConfig(message.getAiid(), message.getOrgi()) ;
		/**
    	 * 替换 无效字符
    	 */
		if(!aiConfig.isEnableother()) {
			message.setMessage(Jsoup.parse(message.getMessage()).text());
		}
		ChatMessage data = null ;
		if(aiConfig.isEnableother()) {
			data = otherAiMessageLevel.process(message , aiMroundsProcesser , aiUser) ;
		}else {
			if(aiUser!=null && !StringUtils.isBlank(aiUser.getBussid()) && !StringUtils.isBlank(aiUser.getDataid())) {	//多轮对话节点
				data = aiMroundsReply.process(aiUser, message, aiUser.getBussid());
			}
			if(data == null || StringUtils.isBlank(data.getMessage())){
				if(aiConfig.isAskfirst()){
					if(aiConfig.isEnableask()){
						data = aiMessageLevel1.process(message , aiMroundsProcesser , aiUser) ; 	//问答库查询
					}
					if(data == null && aiConfig.isEnablescene()){
						data = aiMessageLevel2.process(message , aiMroundsProcesser , aiUser) ;			//场景对话识别
					}
				}else{
					if(aiConfig.isEnablescene()){
						data = aiMessageLevel2.process(message , aiMroundsProcesser , aiUser) ;			//场景对话识别
					}
					if(data == null && aiConfig.isEnableask()){
						data = aiMessageLevel1.process(message , aiMroundsProcesser , aiUser) ; 	//问答库查询
					}
				}
			}
		}
		CousultInvite invite = OnlineUserUtils.cousult(message.getAppid(),message.getOrgi(), UKDataContext.getContext().getBean(ConsultInviteRepository.class));
		if(data == null && !StringUtils.isBlank(aiConfig.getNoresultmsg())){
			data = new ChatMessage();
			data.setAichat(true);
			data.setMessage(aiConfig.getNoresultmsg());
			data.setAppid(message.getAppid());
			data.setUserid(message.getUserid());
			if(invite!=null && !StringUtils.isBlank(invite.getAiname())) {
				data.setUsername(invite.getAiname());
			}else {
				data.setUsername("小E");
			}
			data.setChannel(message.getChannel());
			data.setType(message.getType());
			data.setContextid(message.getContextid());
			data.setOrgi(message.getOrgi());
			data.setMatchtype(UKDataContext.AiMatchType.NO.toString());
			data.setAgentserviceid(message.getAgentserviceid());
			
			if(aiUser!=null) {
				aiUser.setNotmatchnum(aiUser.getNotmatchnum() + 1); 	//增加了无匹配次数	
			}
		}else {
			if(data!=null) {
				data.setAichat(true);
				message.setTopic(data.isTopic());
				message.setTopicid(data.getTopicid());
				data.setSessionid(message.getSessionid());
				data.setAppid(message.getAppid());
				data.setAiid(message.getAiid());
				data.setAgentserviceid(message.getAgentserviceid());
			}
			chatMessageRes.save(message) ;
		}
		/**
		 * 以下代码触发无感知转人工
		 */
		if(invite!=null && invite.isStaticagent() && aiUser != null && data != null) {
			if ((invite.getAsknum() > 0 && aiUser.getUserask() > invite.getAsknum())
					|| (invite.getNotmatchnum() > 0 && aiUser.getNotmatchnum() >= invite.getNotmatchnum())
					|| (invite.getTopictransnum() > 0 && aiUser.getTopictransnum() >= invite.getTopictransnum()) || (invite.isTopicmatch() && data.isStaticagent())) {
				data.setStaticagent(true);
			}else {
				data.setStaticagent(false);
			}
		}
		/**
		 * 触发业务操作
		 */
		if(aiConfig.isBussop() && !StringUtils.isBlank(aiConfig.getBussexeclist()) && aiUser != null) {
			boolean trigger = true ;
			if(!StringUtils.isBlank(aiConfig.getBusslist()) ) {
				String[] codes = aiConfig.getBusslist().split(",") ;
				for(String code : codes) {
					if(aiUser.getNames().containsKey(code) == false) {
						trigger = false ; break ;
					}
				}
			}
			if(trigger == true) {
				final DisUser user = OnlineUserUtils.procesDisUser(aiUser, aiConfig) ;
				if(aiConfig.getBussexeclist().indexOf(UKDataContext.XiaoEBussOP.AGENT.toString()) >= 0 && (StringUtils.isBlank(aiUser.getBusslist()) || aiUser.getBusslist().indexOf(UKDataContext.XiaoEBussOP.AGENT.toString())<0)) {
					if(data!=null) {
						data.setStaticagent(true);
					}
					if(!StringUtils.isBlank(aiUser.getBusslist())) {
						aiUser.setBusslist(aiUser.getBusslist()+",");
					}
					aiUser.setBusslist(aiUser.getBusslist()+UKDataContext.XiaoEBussOP.AGENT.toString());
				}
				if(user!=null) {
					if(aiConfig.getBussexeclist().indexOf(UKDataContext.XiaoEBussOP.CONTACT.toString()) >= 0 && (StringUtils.isBlank(aiUser.getBusslist()) || aiUser.getBusslist().indexOf(UKDataContext.XiaoEBussOP.CONTACT.toString())<0)) {
						if(!StringUtils.isBlank(aiUser.getBusslist())) {
							aiUser.setBusslist(aiUser.getBusslist()+",");
						}
						aiUser.setBusslist(aiUser.getBusslist()+UKDataContext.XiaoEBussOP.CONTACT.toString());
						OnlineUserUtils.processContacts(aiUser, aiConfig , user);
					}
					if(aiConfig.getBussexeclist().indexOf(UKDataContext.XiaoEBussOP.WORKORDER.toString()) >= 0 && (StringUtils.isBlank(aiUser.getBusslist()) || aiUser.getBusslist().indexOf(UKDataContext.XiaoEBussOP.WORKORDER.toString())<0)) {
						if(!StringUtils.isBlank(aiUser.getBusslist())) {
							aiUser.setBusslist(aiUser.getBusslist()+",");
						}
						aiUser.setBusslist(aiUser.getBusslist()+UKDataContext.XiaoEBussOP.WORKORDER.toString());
					}
					if(aiConfig.getBussexeclist().indexOf(UKDataContext.XiaoEBussOP.SMS.toString()) >= 0 && (StringUtils.isBlank(aiUser.getBusslist()) || aiUser.getBusslist().indexOf(UKDataContext.XiaoEBussOP.SMS.toString())<0)) {
						if(!StringUtils.isBlank(aiUser.getBusslist())) {
							aiUser.setBusslist(aiUser.getBusslist()+",");
						}
						aiUser.setBusslist(aiUser.getBusslist()+UKDataContext.XiaoEBussOP.SMS.toString());
						new Timer().schedule(new TimerTask(){  
							public void run(){  
								OnlineUserUtils.processSms(aiUser, aiConfig , user);
							}
						},0);
						
					}
				}
			}
		}
		if(aiUser!=null) {
			/**
			 * 保存会话信息
			 */
			CacheHelper.getAiUserCacheBean().put(aiUser.getUnikey() , aiUser ,UKDataContext.SYSTEM_ORGI) ;
		}
		if(data!=null && data.isSkip() && message.isDebug() == false) {
			data = null ;
		}
		return data ;
	}
	
	public ChatMessage chat(String message , String userid , String appid , String channel , String msgType , String contextid , String orgi , String session){
		ChatMessage chatMessage = new ChatMessage();
		chatMessage.setMessage(message);
		chatMessage.setAppid(!StringUtils.isBlank(appid) ? appid : UKDataContext.SYSTEM_ORGI);
		chatMessage.setUserid(userid);
		chatMessage.setUsername("小E");
		chatMessage.setChannel(channel);
		chatMessage.setCalltype(UKDataContext.CallTypeEnum.IN.toString());
		chatMessage.setType(UKDataContext.MediaTypeEnum.TEXT.toString());
		chatMessage.setContextid(contextid);
		chatMessage.setOrgi(orgi);
		
		chatMessageRes.save(chatMessage) ;
		ChatMessage retChateMessage = chat(chatMessage) ; 
		retChateMessage.setTouser(userid);
		retChateMessage.setUsession(session);
		retChateMessage.setMsgtype(msgType);
		retChateMessage.setCalltype(UKDataContext.CallTypeEnum.OUT.toString());
		chatMessageRes.save(retChateMessage) ;
		return  retChateMessage;
	}

}
